<?php

class SchoolDAO
{
	private $conn;
	private $databaseSelected;
	
	function __construct()
	{
		$this->conn = mysql_connect();
        $this->databaseSelected = mysql_select_db(DB_NAME);
        
        if(!$this->conn || !$this->databaseSelected)
        {
            die('Database connection error in SchoolDAO');
        }
	}

	function findById($id)
	{
		$qry = '
				SELECT 
					*
				FROM 
					school
				WHERE
					idschool = '.$id.'
				';
        $result = mysql_query($qry, $this->conn);
        if(!$result)
        {
            die('Could not retrieve school in SchoolDAO');
        }
		$doodles = array();

		$row = mysql_fetch_array($result);
		$school= new School($row['idschool'], $row['school_name'], $row['school_address1'],$row['school_postcode'], $row['school_state']);
        return $school;
	}
	function findByPartial($needle)
	{
		$qry = '
				SELECT 
					*
				FROM 
					school s
				LEFT JOIN 
					doodle d ON (d.idschool = s.idschool)
				WHERE
					d.year_level IS NOT NULL 
				AND 	d.image_filename IS NOT NULL
				AND	d.student_name IS NOT NULL
				AND
					s.school_name LIKE "'.$needle.'%"
				GROUP BY
					s.idschool
				LIMIT 15;
				';

        $result = mysql_query($qry, $this->conn);
        if(!$result)
        {
            die('Could not retrieve school in SchoolDAO');
        }
		$schools = array();
		
		while($row = mysql_fetch_array($result))
		{
			$schools []= new School($row['idschool'], $row['school_name'], $row['school_address1'],$row['school_postcode'], $row['school_state']);
        }
        return $schools;
	}
}
?>
